package com.woniuxy.cglibproxy;

import com.woniuxy.aspect.MyAspect;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.InvocationHandler;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @Author: 马宇航
 * @Todo: cglib动态代理
 * @DateTime: 01/20/0020 下午 2:14
 * @Component: 成都蜗牛学苑
 **/
public class CglibProxyFactory {
    public static Object getCglibProxy(Object targetClass){
        Object o = Enhancer.create(targetClass.getClass(),
//                new InvocationHandler() {
//            @Override
//            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//                //前置增强
//                MyAspect myAspect = new MyAspect();
//                myAspect.beforeLog();
//                //目标方法
//                Object invoke = method.invoke(targetClass, args);
//                myAspect.afterLog();
//                return invoke;
//            }
//        }
                new MethodInterceptor() {
                    @Override
                    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
                 //前置增强
                MyAspect myAspect = new MyAspect();
                myAspect.beforeLog();
                //目标方法
                Object invoke = proxy.invokeSuper(obj, args);
                myAspect.afterLog();
                return invoke;
                    }
                }
        );
        return o;
    }
}
